package com.dingding.common.core.util.tools.wechat.pay;

import org.apache.log4j.Logger;

import com.dingding.common.core.util.HttpTool;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.XMLParse;
import com.dingding.common.core.util.tools.wechat.pay.paybean.WechatPayOrderQueryResponse;
import com.dingding.common.core.util.tools.wechat.pay.paybean.WechatPayOrderResponse;
import com.dingding.common.core.util.tools.wechat.pay.paybean.request.WechatPayOrderQueryRequest;
import com.dingding.common.core.util.tools.wechat.pay.paybean.request.WechatPayOrderRequest;

public class WechatPayApi {

	private static Logger log = Logger.getLogger(WechatPayApi.class);

	/**
	 * @Title: placeAnOrder @Description:微信下单 当用户在app下单并选择微信支付时，
	 * 服务器向微信支付系统发起初次请求，生成订单 @param request 向微信服务器发送的请求内容 @param
	 * WechatPayOrderResponse 请求结果 @author fengshuonan @throws
	 */
	public WechatPayOrderResponse placeAnOrder(WechatPayOrderRequest request) {

		// 获取请求信息，并转化成xml信息
		String requestXml = XMLParse.toXML(request);

		// 发起http post请求,并获取请求结果
		String responseXml = HttpTool.postXml("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXml);

		log.info("微信返回的数据为：" + responseXml);

		// 如果接收到的请求结果为空
		if (ToolUtil.isBlank(responseXml)) {
			return null;
		}

		// 把xml信息转化成bean
		WechatPayOrderResponse response = XMLParse.toObject(responseXml, WechatPayOrderResponse.class);

		return response;
	}

	/**
	 * @Title: orderQuery @Description: 向微信服务器发送请求，查询订单支付结果是成功 @param request
	 * 查询订单请求封装 @author fengshuonan @return WechatPayOrderResponse
	 * 返回结果封装 @throws
	 */
	public WechatPayOrderQueryResponse orderQuery(WechatPayOrderQueryRequest request) {

		// 获取请求信息，并转化成xml信息
		String requestXml = XMLParse.toXML(request);

		// 发起http post请求,并获取请求结果
		String responseXml = HttpTool.postXml("https://api.mch.weixin.qq.com/pay/orderquery", requestXml);

		// 如果接收到的请求结果为空
		if (ToolUtil.isBlank(responseXml)) {
			return null;
		}

		// 把xml信息转化成bean
		WechatPayOrderQueryResponse response = XMLParse.toObject(responseXml, WechatPayOrderQueryResponse.class);

		return response;
	}
}
